const connection = require('../config/mysql')
const jwt = require('jsonwebtoken')
const secret = 'node-webscoket-chatroom'
connection.connect()
var login = function (params) {
  return new Promise((resolve, reject) => {
    if(!params.username || !params.password) {
      reject({code:400, message: '缺少必要参数'})
    }
    let sql = `select * from user where username = '${params.username}'`
    connection.query(sql, function (error, results, fields) {
      if (error) {
        reject({code: 400, message: error.sqlMessage})
      } else if(!results[0]) {
        resolve({code: 400, message: '用户名错误'})
      } else {
        let sql = `select * from user where password = '${params.password}'`
        connection.query(sql, function (error, results, fields) {
          if (error) {
            reject({code: 400, message: error.sqlMessage})
          } else if(!results[0]) {
            resolve({code: 400, message: '密码错误'})
          } else {
            let payload = {
              username: params.username
            }
            let token = jwt.sign(payload, secret, {
              expiresIn: 60 * 60 * 2
            })
            resolve({code: 200, message: '登录成功', token: token})
          }
        })
      }
    })
  })
}

var userService = {
  login
}

module.exports = userService